import 'dart:async';
import 'dart:convert';
import 'dart:ui';

import 'package:buy_flutter/common/Application.dart';
import 'package:buy_flutter/common/bloc/loading_bloc.dart';
import 'package:buy_flutter/common/sp/UserSharePreference.dart';
import 'package:buy_flutter/common/view/loading.dart';
import 'package:buy_flutter/net/bean/ResponseResultString.dart';
import 'package:buy_flutter/net/bean/UserLoginBean.dart';
import 'package:buy_flutter/net/net_config.dart';
import 'package:buy_flutter/net/net_manager.dart';
import 'package:buy_flutter/net/net_url.dart';
import 'package:buy_flutter/page/login/bloc/counter_bloc.dart';
import 'package:buy_flutter/router/routes.dart';
import 'package:buy_flutter/widgets/common_tabbar_widget.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_verification_box/verification_box.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:logger/logger.dart';

class LoginSmsCodePage extends StatefulWidget {
  String phoneNum = "";
  String countryid = "";

  LoginSmsCodePage(this.phoneNum, this.countryid);

  @override
  State<StatefulWidget> createState() {
    return LoginSmsState(phoneNum, countryid);
  }
}

class LoginSmsState extends State {
  String phoneNum = "";
  String countryid = "";
  String inputCode="";
  LoadingBloc loadingBloc = LoadingBloc();
  CounterBloc _counterBloc = CounterBloc();

  Timer _timer;
  int _curCountDownNum = 60;

  LoginSmsState(this.phoneNum, this.countryid);

  TextEditingController _textEditingController = TextEditingController();
  BuildContext _context;

  @override
  void initState() {
    super.initState();
    getSmsCode();
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: CommonTabbarContainerWidget(
        titleName: "登入啟蒙學習系統",
        buildContext: context,
      ),
      body: MultiBlocProvider(
        providers: [
          BlocProvider(
            create: (context) {
              return loadingBloc;
            },
          ),
          BlocProvider(
            create: (context) {
              return _counterBloc;
            },
          ),
        ],
        child: Container(
          padding: EdgeInsets.all(25),
          child: BlocBuilder<LoadingBloc, bool>(
            builder: (context, state) {
              return Column(
                children: [
                  _topTips(phoneNum),
                  _inputForm(),
                  Align(
                    alignment: Alignment.topRight,
                    child: BlocBuilder<CounterBloc, int>(
                      builder: (context, state) {
                        return Text((state == -1 || _curCountDownNum <= 0)
                            ? ""
                            : "尚餘：$_curCountDownNum秒");
                        return state == -1
                            ? GestureDetector(
                                onTap: () {
                                  startCountDown();
                                },
                                child: Text("重新发送"),
                              )
                            : Text("尚餘：$_curCountDownNum秒");
                      },
                    ),
                  ),
                  _loginButton(context),
                  BlocBuilder<CounterBloc, int>(builder: (context, state) {
                    print("state=,CounterBloc===>${state}");
                    return (state == -1)
                        ? GestureDetector(
                            child: Padding(
                              padding: const EdgeInsets.all(15),
                              child: Text(
                                "重新發送",
                                style: TextStyle(
                                  color: Color(0xff595959),
                                  fontSize: 15,
                                ),
                              ),
                            ),
                            onTap: () {
                              getSmsCode();
                            },
                          )
                        : Container();
                  })
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  Widget _topTips(String phone) {
    return Column(
      children: [
        Image.asset(
          "assets/login/ic_input_code_top.png",
          height: 100,
        ),
        Text(
          "請輸入6位數字認證碼",
          style: TextStyle(color: Colors.black, fontSize: 20,fontWeight: FontWeight.bold),
          textAlign: TextAlign.center,
        ),
        SizedBox(
          height: 10,
        ),
        Text(
          "我們已傳送認證碼至以下號碼",
          style: TextStyle(color: Color(0xFF595959), fontSize: 16),
        ),
        Text(
          "****${phone.length <= 4 ? phone : phone.substring(phone.length - 4)}",
          style: TextStyle(color: Color(0xFF9124A3), fontSize: 16),
        ),
      ],
    );
  }

  Widget _inputForm() {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 20),
      height: 50,
      child: VerificationBox(

        itemWidget: 50,
        count: 6,
        borderColor: Color(0xFFECEDED),
        focusBorderColor: Color(0xFF58C7B7),
        borderWidth: 2,
        borderRadius: 6,
        showCursor: true,
        cursorColor: Color(0xFF58C7B7),
        cursorWidth: 2,
        cursorIndent: 10,
        cursorEndIndent: 10,
        textStyle: TextStyle(
          color: Color(0xFF00AF96),
          fontSize: 20,
        ),
        onSubmitted: (value) {
          inputCode=value;
        },
      ),
    );
  }

  // Widget _inputForm() {
  //   return Container(
  //       margin: EdgeInsets.symmetric(vertical: 20),
  //       padding: EdgeInsets.symmetric(horizontal: 8),
  //       height: 50,
  //       decoration: BoxDecoration(
  //         border: Border.all(color: Color(0xFFECEDED), width: 1),
  //         borderRadius: BorderRadius.only(
  //           topRight: Radius.circular(5),
  //           bottomRight: Radius.circular(5),
  //         ),
  //       ),
  //       child: TextField(
  //         controller: _textEditingController,
  //         keyboardType: TextInputType.number,
  //         inputFormatters: [
  //           WhitelistingTextInputFormatter.digitsOnly,
  //         ],
  //         style: TextStyle(
  //           color: Color(0xFF00AF96),
  //           fontSize: 20,
  //         ),
  //         textAlign: TextAlign.justify,
  //         decoration: InputDecoration(
  //           contentPadding: EdgeInsets.all(0),
  //           border: InputBorder.none,
  //         ),
  //       ));
  // }

  Widget _loginButton(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        loginUser();
      },
      child: Text("驗證"),
      style: ButtonStyle(
        minimumSize: MaterialStateProperty.all(Size(120, 40)),
        textStyle: MaterialStateProperty.all(TextStyle(color: Colors.white)),
        backgroundColor: MaterialStateProperty.all(Color(0xFF58C7B7)),
        shape: MaterialStateProperty.all(
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(20))),
      ),
    );
  }

  void loginUser() async {
    if (inputCode == null || inputCode.length != 6) {
      Fluttertoast.showToast(msg: "请输入正确的验证码");
      return;
    }

    Map<String, dynamic> querData = {
      "mobile": phoneNum,
      "countryid": countryid,
      "code": inputCode,
    };

    Response<String> response = await NetManager.getInstance()
        .post<String>(NetUrls.net_user_login, data: FormData.fromMap(querData));

    if (response != null && response.data.isNotEmpty) {
      Logger().i(response.data);

      UserLoginBean userLoginBean =
          UserLoginBean.fromJson(json.decode(response.data));

      if (userLoginBean != null) {
        if (userLoginBean.code == 200 && userLoginBean.data.jwt.isNotEmpty) {
          UserSharePreference.addUser(userLoginBean);
          Application.router
              .navigateTo(_context, Routes.home, clearStack: true);
        } else {
          String errorMsg = userLoginBean.message;
          if (errorMsg.isNotEmpty) {
            Fluttertoast.showToast(msg: errorMsg);
          }
        }
      }
    }
  }

  getSmsCode() async {
    Map<String, String> map = {"mobile": phoneNum, "countryid": countryid};

    Logger().d(map.toString());
    var formData = FormData.fromMap(map);

    try {
      Logger().d("====访问网络====");
      Response<String> responseResult =
          await NetManager.getInstance().post<String>(
        NetUrls.net_login_send_sms,
        data: formData,
      );
      String response = responseResult.data;
      Logger().d(response);
      if (response != null) {
        ResponseResultString responseResultString =
            ResponseResultString.fromJson(json.decode(response));
        if (responseResultString != null && responseResultString.code == 200) {
          startCountDown();
        }
        if (responseResultString != null &&
            responseResultString.message.isNotEmpty) {
          Fluttertoast.showToast(msg: responseResultString.message);
        }
      }
    } catch (e) {
      Logger().d("error==>:" + e.toString());
      Fluttertoast.showToast(msg: "获取验证码失败,请重新获取");
      _counterBloc.add(CounterEvent.complete);
    } finally {
      // Loading.dismiss(_context);
    }
  }

  void startCountDown() {
    if (_timer == null) {
      _curCountDownNum = 60;
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        if (_curCountDownNum == 0) {
          _counterBloc.add(CounterEvent.complete);
          cancelTimer();
        } else {
          _curCountDownNum--;
          _counterBloc.add(CounterEvent.increment);
        }
      });
    }
  }

  void cancelTimer() {
    if (_timer != null) {
      if (_timer.isActive) {
        _timer.cancel();
        _timer = null;
      }
    }
  }

  @override
  void dispose() {
    cancelTimer();
    super.dispose();
  }
}
